package com.etc.my.filter;

import com.etc.my.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter({"/head.jsp","/foot.jsp","/mycar.jsp","/mycollection.jsp","/myfavorite.jsp","/myreserve.jsp","/mywantsellcar.jsp","/order.jsp","/reserve.jsp","/sellcar.jsp","/userhome.jsp"})
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;//强制转型
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取session登录的用户
        User user = (User) request.getSession().getAttribute("loginuser");
        if(user==null){
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print("<script>alert('您未登录，请登录！');location.href='user_login.jsp'</script>");
        }else{
            chain.doFilter(req, resp);
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
